xquery version "0.9-ml"

(: $root is a string representing the root node from which the id will be checked and the node to be updated will be calculted 
$id is the id of the node to update
$node is the node to update from the the end of the provided root
$value is the value the nodes text will updated to

the entire query is put into a string and evaluated because when mixing standard query evaluations with those that had been evaluated from a string, an error was thrown stating that external nodes could not be updated

further, within the string, there is no guarantee that a node will have a value. Text() returns an error when evaluating against an empty element. So when inserting values we need to construct the lowest level element repersentation of the value e.g. <tag>val</tag>
:)

let $arg_root := xdmp:get-request-field("root")
let $arg_id := xdmp:get-request-field("id")
let $arg_node := xdmp:get-request-field("node")
let $arg_value := xdmp:get-request-field("value")

(:these variables are for testing :)
(:
let $arg_root := "doc('wines.xml')/wines/wine"
let $arg_id := "10090"
let $arg_node := "name"
let $arg_value := "supername"
:)

(: check to see if the node has any value 
   if there is a value, the commmand will replace the value
   if there is no value, check to see if the node exists
   if there is a node, insert the value
   if there is no node, create the node with value and insert the new node:)
let $cmd := if ( xdmp:eval(concat($arg_root,"[@id=",$arg_id,"]/",$arg_node,"/child::text()")) )
then concat(" xdmp:node-replace($r/", $arg_node, "/child::text() , text {'", $arg_value, "' } )")
else if ( xdmp:eval(concat($arg_root,"[@id=",$arg_id,"]/",$arg_node) ) )
	then concat(" xdmp:node-insert-child($r/", $arg_node, ", text {'", $arg_value, "' } )")
	else concat(" xdmp:node-insert-child($r,", "<",$arg_node," dateCreated='",fn:current-dateTime(),"' dateModified=''>", $arg_value, "</",$arg_node,"> )")


let $s := concat(

				 "let $root := ",$arg_root, " for $r in $root ",

				 " where $r/@id=",$arg_id, "
				 ",

				 " return 
				 ",

				 $cmd

				  )
return
xdmp:eval($s),
<result>
    true
</result>







